import request from '/@/utils/request';

export const pageList = (params?: Object) => {
	return request({
		url: '/admin/menu/tree',
		method: 'get',
		params,
	});
};

export const details = (obj: object) => {
	return request({
		url: `/admin/menu/details`,
		method: 'get',
		params: obj,
	});
};

export const save = (data: Object) => {
	return request({
		url: '/admin/menu',
		method: 'post',
		data: data,
	});
};

export const putObj = (data: Object) => {
	return request({
		url: '/admin/menu',
		method: 'put',
		data: data,
	});
};

export const addObj = (data: Object) => {
	return request({
		url: '/admin/menu',
		method: 'post',
		data: data,
	});
};

export const delObj = (id: string) => {
	return request({
		url: '/admin/menu/' + id,
		method: 'delete',
	});
};

/**
 * 后端控制路由，isRequestRoutes 为 true，则开启后端控制路由
 * @method getAdminMenu 获取后端动态路由菜单(admin)
 */
export function useMenuApi() {
	return {
		getAdminMenu: (params?: object) => {
			const env = import.meta.env.PROD;
			if (env) {
				params = { ...params, appCode: 'irspmgt' };
			}
			return request({
				url: '/admin/menu',
				method: 'get',
				params: { ...params, appCode: 'irspmgt' },
			});
		},
	};
}

export function validatePermission(rule: any, value: any, callback: any, isEdit: boolean) {
	if (isEdit) {
		return callback();
	}

	details({ permission: value }).then((response) => {
		const result = response.data;
		if (result !== null) {
			callback(new Error('标识已经存在'));
		} else {
			callback();
		}
	});
}

export function validatePath(rule: any, value: any, callback: any, isEdit: boolean) {
	if (isEdit) {
		return callback();
	}

	details({ path: value }).then((response) => {
		const result = response.data;
		if (result !== null) {
			callback(new Error('路径已经存在'));
		} else {
			callback();
		}
	});
}
